package com.study.spmongodb.wwj.juc.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;
import java.util.stream.Collectors;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 20:37
 */
public class StampedLockExample1 {

    private static final StampedLock lock = new StampedLock();

    private final static List<Long> DATA = new ArrayList<>();


    public static void main(String[] args) {
        final ExecutorService executor = Executors.newFixedThreadPool(10);
        Runnable readTask = () -> {
            for (; ; ) {
                read();
            }
        };
        Runnable writeTask = () -> {
            for (; ; ) {
                write();
            }
        };

        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(readTask);
        executor.submit(writeTask);

    }

    private static void read() {
        long stamped = -1;
        try {
            stamped = lock.readLock();
            final String collect = DATA.stream().map(String::valueOf).collect(Collectors.joining("#", "R-", ""));
            Optional.of(collect).ifPresent(System.out::println);
        } finally {
            lock.unlockRead(stamped);
        }
    }

    private static void write() {
        long stamped = -1;
        try {
            stamped = lock.writeLock();
            DATA.add(System.currentTimeMillis());
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            lock.unlockWrite(stamped);
        }
    }
}
